package com.example.demo.service.impl;

import com.example.demo.common.ResponseCode;
import com.example.demo.common.ServerResponse;
import com.example.demo.entity.User;

import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import com.google.code.kaptcha.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public ServerResponse login(String username, String password,String check) {
        //获取httpservletrequest
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //找到request请求的cleck
        String cCheck=(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //检查验证码，抛出错误
        if (!cCheck.equals(check))return new ServerResponse<>(ResponseCode.ERROR.getCode(), "验证码不正确",null);
        //检查用户不存在的情况
        if (userMapper.checkUsername(username) == 0) return new ServerResponse<>(ResponseCode.ERROR.getCode(), "用户不存在", null);
        User user = userMapper.login(username, password);
        //登录
        if (user == null) return new ServerResponse<>(ResponseCode.ERROR.getCode(), "密码不正确", null);
        user.setPassword("");
        return new ServerResponse<>(ResponseCode.SUCCESS.getCode(), "登录成功", user);

    }

    @Override
    public ServerResponse register(User user) {
        int count=userMapper.checkUsername(user.getUsername());
        if(count!=0){
            return new ServerResponse<>(ResponseCode.ERROR.getCode(), "注册失败!用户已存在",null);
        }else{
            if(user.getBirthday()==""){
                user.setBirthday("2000-01-01");
            }
            userMapper.register(user);
            return ServerResponse.succRegiser("注册成功");
        }
    }
}
